import { uploadFile } from '@/api/fileUpload';
import type { RequestMethodResponse, UploadFile } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';

/**
 * 检查文件大小是否在限制范围内
 * @param file 文件对象
 * @param maxSizeMB 最大文件大小（MB）
 * @param showError 是否显示错误提示
 * @returns boolean
 */
export const checkFileSize = (file: UploadFile | File, maxSizeMB: number = 5, showError: boolean = true): boolean => {
  const maxSize = maxSizeMB * 1024 * 1024; // 转换为字节
  const isWithinLimit = file.size < maxSize;

  if (!isWithinLimit && showError) {
    const currentSize = (file.size / 1024 / 1024).toFixed(2);
    MessagePlugin.error(`文件大小不能超过${maxSizeMB}MB，当前文件大小：${currentSize}MB`);
  }

  return isWithinLimit;
};

/**
 * 检验文件类型（仅允许jpeg, jpg, png）
 * @param file 文件对象
 * @returns boolean
 */
export const checkFileType = (file: UploadFile | File): boolean => {
  const fileType = file.type;
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
  console.log('fileType', fileType);
  return allowedTypes.includes(fileType);
};

/**
 * 通用文件上传函数
 * @param file 文件对象（UploadFile 或 File）
 * @param onSuccess 上传成功回调，参数为文件URL
 * @param isUserAvatar 是否是用户头像上传
 * @returns Promise<RequestMethodResponse>
 */
export const commonFileUpload = async (
  file: UploadFile | File,
  isUserAvatar: boolean,
  onSuccess?: (url: string) => void,
): Promise<RequestMethodResponse> => {
  const formDataObj = new FormData();
  // 处理不同类型的文件对象
  if (file instanceof File) {
    // 原生 File 对象
    formDataObj.append('file', file);
  } else {
    // UploadFile 对象
    formDataObj.append('file', file.raw);
  }

  if (isUserAvatar) {
    formDataObj.append('isUserAvatar', 'true');
  } else {
    formDataObj.append('isUserAvatar', 'false');
  }

  try {
    const res = await uploadFile(formDataObj);
    console.log('res', res);
    const url = res.data?.data;

    if (url) {
      console.log('url', url);
      // 调用成功回调
      if (onSuccess) {
        console.log('url', url);
        onSuccess(url);
      }

      return Promise.resolve({ status: 'success', response: { url } });
    } else {
      return Promise.resolve({
        status: 'fail',
        error: '网络异常，文件上传失败',
        response: { url: '' },
      });
    }
  } catch (error) {
    return Promise.resolve({
      status: 'fail',
      error: '网络异常，文件上传失败',
      response: { url: '' },
    });
  }
};
